package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.JzdxDepartConvert;
import com.engine4cloud.tdf.supervision.dto.create.JzdxDepartCreateDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxDepartResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.JzdxDepartUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.JzdxDepartEntity;
import com.engine4cloud.tdf.supervision.mapper.JzdxDepartMapper;
import com.engine4cloud.tdf.supervision.service.JzdxDepartService;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 矫正对象所属四级部门
 *
 * @author wenjie
 * @date 2024-04-03 09:22:19
 */
@Service
public class JzdxDepartServiceImpl extends ServiceImpl<JzdxDepartMapper, JzdxDepartEntity> implements JzdxDepartService {
    @Override
    public Boolean create(JzdxDepartCreateDTO dto) {
        return save(JzdxDepartConvert.INSTANCE.create(dto.getRybh(), SecurityUtils.getUser().getTenantId(), dto.getVillage(), dto.getCountry(), dto.getCity(), dto.getProvince()));
    }

    @Override
    public JzdxDepartResultDTO findByCode(String code) {
        return JzdxDepartConvert.INSTANCE.convert(getOne(wrapper(code)));
    }

    @Override
    public Boolean update(JzdxDepartUpdateDTO dto) {
        JzdxDepartEntity entity = Optional.ofNullable(this.getOne(wrapper(dto.getRybh())))
                .orElseThrow(() -> new ValidateCodeException("矫正对象部门数据不存在"));

        return updateById(JzdxDepartConvert.INSTANCE.update(entity.getId(), dto.getVillage(), dto.getCountry(), dto.getCity(), dto.getProvince()));
    }

    private LambdaQueryWrapper<JzdxDepartEntity> wrapper(String code) {
        LambdaQueryWrapper<JzdxDepartEntity> wrapper = Queries.lambda();
        Queries.accept(code, v -> wrapper.eq(JzdxDepartEntity::getRybh, v));
        return wrapper;
    }
}